package com.codedancer.campus.manager.schedule;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.codedancer.campus.common.dataresource.TianXinData;
import com.codedancer.campus.common.model.tx.HeadlineNewsModel;
import com.codedancer.campus.mapper.HeadlineNewsMapper;
import com.codedancer.campus.po.HeadlineNews;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 头条新闻定时任务拉取
 */
@Component
@Slf4j
public class HeadlineNewsSchedule {

    @Autowired
    private TianXinData tianXinData;
    @Autowired
    private HeadlineNewsMapper headlineNewsMapper;

    /**
     * 每隔五分钟拉去头条新闻
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void pullHeadlineNews() {
        log.info("开始拉取头条新闻");
        int putStorage = 0;
        List<HeadlineNewsModel> headlineNewsModels = tianXinData.getHeadlineNews();
        if (CollUtil.isNotEmpty(headlineNewsModels)) {
            for (HeadlineNewsModel headlineNewsModel : headlineNewsModels) {
                if (headlineNewsMapper.existsByUuId(headlineNewsModel.getId())) {
                    continue;
                }
                HeadlineNews headlineNews = BeanUtil.copyProperties(headlineNewsModel,
                    HeadlineNews.class);
                headlineNews.setUuid(headlineNewsModel.getId());
                headlineNews.setPublishDate(
                    DateUtil.parse(headlineNewsModel.getCtime(), "yyyy-MM-dd HH:mm:ss"));
                headlineNews.setCoverImage(headlineNewsModel.getPicUrl());
                headlineNewsMapper.insert(headlineNews);
                putStorage++;
            }
            log.info("头条新闻拉取成，入库成功，入库数量：{}", putStorage);
            return;
        }
        log.info("拉取的头条新闻数据为空");
    }
}
